<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="时间" prop="date">
        <el-date-picker v-model="dateRange" type="daterange" unlink-panels value-format="YYYY-MM-DD" format="YYYY-MM-DD"
          range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" :shortcuts="shortcuts"
          @change="changeDate" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport">导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
    </el-row>
    <el-table v-horizontal-scroll="'always'" v-loading="loading" :data="userList"
      @selection-change="handleSelectionChange" :show-summary="true" border :summary-method="summaryMethod">
      <el-table-column label="提单年" prop="提单年"></el-table-column>
      <el-table-column label="提单月" prop="提单月"></el-table-column>
      <el-table-column label="运营商" prop="运营商"></el-table-column>
      <el-table-column label="面值" prop="面值"></el-table-column>
      <el-table-column label="套餐id" prop="套餐id"></el-table-column>
      <el-table-column label="套餐名称" prop="套餐名称" width="200"></el-table-column>
      <el-table-column label="激活数" prop="激活数"></el-table-column>
      <el-table-column label="结佣数" prop="结佣数"></el-table-column>

      <!-- 动态生成领取数、占激活领取率、占结佣领取率列 -->
      <el-table-column label="领取数" prop="领取数" align="center">
        <el-table-column v-for="(year, yearIndex) in dynamicYears" :key="year" :label="year + ''" align="center">
          <template #default="scope">
            <el-table-column v-for="(month, monthIndex) in monthsForYear(year)" :key="month" :label="month"
              align="center">
              <template #default="scope">
                <!-- 动态显示数据 -->
                <div style="text-align: center;">{{ getDataForMonth(scope.row, year, month) }}</div>
              </template>
            </el-table-column>
          </template>
        </el-table-column>
      </el-table-column>
      <el-table-column label="占激活领取率" prop="占激活领取率" align="center">
        <el-table-column v-for="(year, yearIndex) in dynamicYears" :key="year" :label="year + ''" align="center">
          <template #default="scope">
            <el-table-column v-for="(month, monthIndex) in monthsForYear(year)" :key="month" :label="month"
              align="center">
              <template #default="scope">
                <!-- 动态显示数据 -->
                <div style="text-align: center;">{{ getDataForMonth1(scope.row, year, month) }}</div>
              </template>
            </el-table-column>
          </template>
        </el-table-column>
      </el-table-column>
      <el-table-column label="占结佣领取率" prop="占结佣领取率" align="center">
        <el-table-column v-for="(year, yearIndex) in dynamicYears" :key="year" :label="year + ''" align="center">
          <template #default="scope">
            <el-table-column v-for="(month, monthIndex) in monthsForYear(year)" :key="month" :label="month"
              align="center">
              <template #default="scope">
                <!-- 动态显示数据 -->
                <div style="text-align: center;">{{ getDataForMonth2(scope.row, year, month) }}</div>
              </template>
            </el-table-column>
          </template>
        </el-table-column>
      </el-table-column>
    </el-table>
  </div>
</template>

<script setup name="Rate">
import { shortcuts, Y, M, D } from '@/utils/dateSet'
import { parseTime } from "@/utils/ruoyi.js";
import { listExcel } from "@/api/phoneBill/rate";

const { proxy } = getCurrentInstance();

const userList = ref([]);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const totalData = ref({}); // 合计数据
const dateRange = ref([
  parseTime(new Date(Y.value, M.value, D.value).getTime() - 3600 * 1000 * 24 * 30),
  parseTime(new Date(Y.value, M.value, D.value).getTime())
]);

// 列显隐信息
const columns = ref([]);

const data = reactive({
  form: {},
  queryParams: {
    type: 1
  },
  rules: {},
});

const { queryParams, form } = toRefs(data);

const changeDate = (val) => {
  if (!val) {
    dateRange.value = []
  } else {
    queryParams.value.startTime = dateRange.value[0];
    queryParams.value.endTime = dateRange.value[1];
  }

};
/** 查询列表 */
async function getList() {
  loading.value = true;
  await listExcel(proxy.addDateRange({
    ...queryParams.value,
    startTime: dateRange.value ? dateRange.value[0].split(' ')[0] : '',
    endTime: dateRange.value ? dateRange.value[1].split(' ')[0] : '',
  })).then(
    (res) => {
      loading.value = false;
      totalData.value = res.total;
      // 转换函数
      userList.value = res.list.map(item => {
        // 处理领取数
        const 领取数 = [];
        for (const year in item["领取数"]) {
          const yearObj = {
            year: parseInt(year),
            children: []
          };

          for (const month in item["领取数"][year]) {
            yearObj.children.push({
              month: month,
              value: item["领取数"][year][month] || "" // 处理空值
            });
          }

          领取数.push(yearObj);
        }

        // 处理占激活领取率
        const 占激活领取率 = [];
        for (const year in item["占激活领取率"]) {
          const yearObj = {
            year: parseInt(year),
            children: []
          };

          for (const month in item["占激活领取率"][year]) {
            yearObj.children.push({
              month: month,
              value: item["占激活领取率"][year][month] || "" // 处理空值
            });
          }

          占激活领取率.push(yearObj);
        }

        // 处理占结佣领取率
        const 占结佣领取率 = [];
        for (const year in item["占结佣领取率"]) {
          const yearObj = {
            year: parseInt(year),
            children: []
          };

          for (const month in item["占结佣领取率"][year]) {
            yearObj.children.push({
              month: month,
              value: item["占结佣领取率"][year][month] || "" // 处理空值
            });
          }

          占结佣领取率.push(yearObj);
        }

        // 返回转换后的数据
        return {
          领取数,
          提单年: item["提单年"],
          提单月: item["提单月"],
          运营商: item["运营商"],
          面值: item["面值"],
          套餐id: item["套餐id"],
          套餐名称: item["套餐名称"],
          激活数: item["激活数"],
          结佣数: item["结佣数"],
          占激活领取率,
          占结佣领取率
        };
      });
    }
  );
}

// 获取动态年份
const dynamicYears = computed(() => {
  const years = new Set();
  userList.value.forEach(row => {
    row.领取数.forEach(entry => {
      years.add(entry.year);
    });
    row.占激活领取率.forEach(entry => {
      years.add(entry.year);
    });
    row.占结佣领取率.forEach(entry => {
      years.add(entry.year);
    });
  });
  return Array.from(years);
});

// 获取每个年份对应的月份列表
const monthsForYear = (year) => {
  const months = new Set();
  userList.value.forEach(row => {
    row.领取数.forEach(entry => {
      if (entry.year === year) {
        entry.children.forEach(child => {
          months.add(child.month);
        });
      }
    });
    row.占激活领取率.forEach(entry => {
      if (entry.year === year) {
        entry.children.forEach(child => {
          months.add(child.month);
        });
      }
    });
    row.占结佣领取率.forEach(entry => {
      if (entry.year === year) {
        entry.children.forEach(child => {
          months.add(child.month);
        });
      }
    });
  });
  return Array.from(months);
};

// 根据年份和月份从数据中提取值
const getDataForMonth = (row, year, month) => {
  const data = row.领取数.find(entry => entry.year === year);
  if (!data) return "";
  const monthData = data.children.find(child => child.month === month);
  return monthData ? monthData.value : "";
};

const getDataForMonth1 = (row, year, month) => {
  const data = row.占激活领取率.find(entry => entry.year === year);
  if (!data) return "";
  const monthData = data.children.find(child => child.month === month);
  return monthData ? monthData.value : "";
};

const getDataForMonth2 = (row, year, month) => {
  const data = row.占结佣领取率.find(entry => entry.year === year);
  if (!data) return "";
  const monthData = data.children.find(child => child.month === month);
  return monthData ? monthData.value : "";
};

const summaryMethod = ({ columns, data }) => {
  const sums = [];

  // 对需要合计的列（激活数、结佣数、领取数、占激活领取率、占结佣领取率）进行合计
  columns.forEach((column, index) => {
    // console.log(index, 9999)

    if (index === 0) {
      sums.push("合计"); // 第一列显示合计
    }
    else if (column.label === "激活数") {
      // 合计“激活数”和“结佣数”
      sums.push(totalData.value['激活数']);
    }
    else if (column.label === "结佣数") {
      // 合计“激活数”和“结佣数”
      sums.push(totalData.value['结佣数']);
    }
    else if (index == 8) {
      dynamicYears.value.forEach(year => {
        monthsForYear(year).forEach(month => {
          sums.push(totalData.value['领取数']?.[year]?.[month] || 0);
        });
      });

    }
    else if (index == 9) {
      dynamicYears.value.forEach(year => {
        monthsForYear(year).forEach(month => {
          sums.push(totalData.value['占激活领取率']?.[year]?.[month] || 0);
        });
      });

    }
    else if (index == 10) {
      dynamicYears.value.forEach(year => {
        monthsForYear(year).forEach(month => {
          sums.push(totalData.value['占结佣领取率']?.[year]?.[month] || 0);
        });
      });

    }
    else {
      sums.push("");
    }
  });
  // console.log(sums)
  return sums;
};
/** 搜索按钮操作 */
async function handleQuery() {
  await getList();

}
/** 重置按钮操作 */
function resetQuery() {
  dateRange.value = [parseTime(new Date(Y.value, M.value, D.value).getTime() - 3600 * 1000 * 24 * 30),
  parseTime(new Date(Y.value, M.value, D.value).getTime())]
  proxy.resetForm("queryRef");
  queryParams.value.deptId = undefined;
  queryParams.value.startTime = undefined;
  queryParams.value.endTime = undefined;
  // proxy.$refs.deptTreeRef.setCurrentKey(null);
  handleQuery();
}
/** 选择条数  */
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}
/** 导出操作 */
function handleExport() {
  proxy.download(
    "/receiveRate/export",
    {
      ...queryParams.value,
      startTime: dateRange.value ? dateRange.value[0].split(' ')[0] : '',
      endTime: dateRange.value ? dateRange.value[1].split(' ')[0] : '',
    },
    `话费领取费率-${new Date().getTime()}.xlsx`
  );
}
getList();
</script>
<style scoped>
:deep(.el-table__footer-wrapper) {
  position: fixed;
  bottom: 0;
  background-color: #fff;
  z-index: 1;
}
</style>